<template>
  <div class="app-container">
    <nav v-if="showMainNav" class="nav-bar">
      <router-link to="/tasks">任务列表</router-link>
      <router-link to="/upload">上传文件</router-link>
      <router-link to="/statistics">数据统计</router-link>
      <div class="user-info" v-if="user">
        <span>{{ user.username }}</span>
        <button @click="handleLogout">退出</button>
      </div>
    </nav>
    <nav v-if="showLoginNav" class="login-nav">
      <router-link to="/login">登录</router-link>
      <router-link to="/register">注册</router-link>
    </nav>
    <router-view @login-success="updateNavigation"></router-view>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, watch } from 'vue'
import { useRouter, useRoute } from 'vue-router'

const router = useRouter()
const route = useRoute()
const user = ref(null)

// 计算是否显示主导航栏
const showMainNav = computed(() => {
  return route.path !== '/login' && route.path !== '/register' && user.value
})

// 计算是否显示登录导航栏
const showLoginNav = computed(() => {
  return (route.path === '/login' || route.path === '/register') && !user.value
})

// 更新用户信息和导航状态
const updateNavigation = () => {
  const userStr = localStorage.getItem('user')
  user.value = userStr ? JSON.parse(userStr) : null
}

// 监听路由变化
watch(route, () => {
  updateNavigation()
})

// 处理退出登录
const handleLogout = () => {
  localStorage.removeItem('user')
  user.value = null
  router.push('/login')
}

// 组件挂载时初始化
onMounted(() => {
  updateNavigation()
})
</script>

<style>
.app-container {
  font-family: Arial, sans-serif;
}

body {
  margin: 0;
  padding: 0;
  background-color: #f5f5f5;
}

.nav-bar {
  background-color: #fff;
  padding: 1rem;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
  display: flex;
  align-items: center;
  gap: 20px;
}

.nav-bar a {
  color: #333;
  text-decoration: none;
  padding: 0.5rem 1rem;
  border-radius: 4px;
  transition: background-color 0.3s;
}

.nav-bar a:hover {
  background-color: #f0f0f0;
}

.nav-bar a.router-link-active {
  color: #4CAF50;
  font-weight: bold;
}

.user-info {
  margin-left: auto;
  display: flex;
  align-items: center;
  gap: 10px;
}

.user-info span {
  color: #666;
}

.user-info button {
  padding: 6px 12px;
  background-color: #f44336;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  transition: background-color 0.3s;
}

.user-info button:hover {
  background-color: #d32f2f;
}

/* 内容区域样式 */
.app-container > :not(.nav-bar) {
  padding: 20px;
}

/* 登录导航栏样式 */
.login-nav {
  background-color: #fff;
  padding: 1rem;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
  display: flex;
  align-items: center;
  gap: 20px;
  justify-content: center;
}

.login-nav a {
  color: #333;
  text-decoration: none;
  padding: 0.5rem 1rem;
  border-radius: 4px;
  transition: background-color 0.3s;
}

.login-nav a:hover {
  background-color: #f0f0f0;
}

.login-nav a.router-link-active {
  color: #4CAF50;
  font-weight: bold;
}
</style>
